package com.zhong.media;


import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;

import com.danikula.videocache.CacheListener;
import com.danikula.videocache.HttpProxyCacheServer;

import java.io.File;

public class MyVideoActivity extends Activity  implements CacheListener {
	private static final String TAG = MediaPlayerActivity.class.getSimpleName();
	private MyVideoView mVideoView;
	private String url;
	private Uri uri;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
					WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_my_video);
		
		Intent intent = getIntent();
		if(intent != null){
			url = intent.getStringExtra("url");
		}
		
		if(url != null){
			initView();
		} else {
			MyVideoActivity.this.finish();
		}
	}

	private void initView() {
		mVideoView = (MyVideoView) findViewById(R.id.video);
//		Uri uri = Uri.parse("http://forum.ea3w.com/coll_ea3w/attach/2008_10/12237832415.3gp");
		uri = Uri.parse(url);
//		mVideoView.setMediaController(new MediaController(this)); 
//		mVideoView.setVideoURI(uri);
//		mVideoView.start();
		mVideoView.requestFocus();	
		mVideoView.setOnCompletionListener(new OnCompletionListener() {
			
			@Override
			public void onCompletion(MediaPlayer mp) {
				MyVideoActivity.this.finish();
			}
		});

		startVideo();
	}

	private void startVideo() {
		HttpProxyCacheServer proxy = MyApplication.getProxy(this);
		proxy.registerCacheListener(this, url);
		String proxyUrl = proxy.getProxyUrl(url);
		Log.d(TAG, "Use proxy url " + proxyUrl + " instead of original url " + url);
		mVideoView.setVideoPath(url);
		mVideoView.start();
	}

	@Override
	public void onCacheAvailable(File cacheFile, String url, int percentsAvailable) {
		Log.d(TAG, String.format("onCacheAvailable. percents: %d, file: %s, url: %s", percentsAvailable, cacheFile, url));
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		MyApplication.getProxy(this).unregisterCacheListener(this);
	}
}
